package cn.edu.zjicm.wordsnet_d.activity;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.DateTimeReceiver;
import cn.edu.zjicm.wordsnet_d.BroadcastReceiver.HomeKeyEventBroadCastReceiver;
import cn.edu.zjicm.wordsnet_d.adapter.VerticalPagerAdapter;
import cn.edu.zjicm.wordsnet_d.adapter.WordDetailForLockAdapter;
import cn.edu.zjicm.wordsnet_d.data.OneWord;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.fragment.WordDetailForLockFragment;
import cn.edu.zjicm.wordsnet_d.util.BitmapUtil;
import cn.edu.zjicm.wordsnet_d.util.LogUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;
import cn.edu.zjicm.wordsnet_d.view.HorizontalViewPager;
import cn.edu.zjicm.wordsnet_d.view.PageControl;
import cn.edu.zjicm.wordsnet_d.view.VerticalViewPager;
import cn.edu.zjicm.wordsnet_d.view.viewPagerParent;

import com.umeng.analytics.MobclickAgent;

public class LockActivity extends FragmentActivity {

	private List<OneWord> mWordList;
	private ArrayList<Fragment> fragmentsList;
	private ArrayList<View> verticalPagerViewList;
	private ArrayList<View> parentPagerViewList;
	// Views
	private View viewChild;
	private LinearLayout mLockHeadContainer;
	private ImageView mLockBottom;
	private ImageView mBackgroundImage;
	private HorizontalViewPager mPagerChild;
	private viewPagerParent mPagerParent;
	private VerticalViewPager mVerticalViewPager;
	private FragmentStatePagerAdapter mPagerAdapter;
	private static boolean isParentSlidEnable;

	private static final int OFFSCREEN_PAGE_LIMIT = 8;
	public static Context mContext;
	private static TextView date_text, time_text, power_text;
	private DateTimeReceiver dateTimerReceiver;
	private HomeKeyEventBroadCastReceiver homeKeyReceiver;
	private TelephonyManager tm;
	private PageControl lock1234;
	private int[] bitmaps;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = LockActivity.this;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_lock);
		// LogUtil.addLog("LockActivity onCreate()开始锁屏界面运行");
		findViews();
		initViews();
		setBackGround();
		Utils.immersionStatusBarForXiaoMi(LockActivity.this);
	}

	private void findViews() {
		// LogActivity.addLog("LockActivity findViews()");
		mVerticalViewPager = (VerticalViewPager) findViewById(R.id.vertical_viewpager);
		findInsideView();
	}

	public View findInsideView() {
		// LogActivity.addLog("LockActivity findInsideView()");
		viewChild = View.inflate(this, R.layout.activity_lock_inside, null);
		mPagerChild = (HorizontalViewPager) viewChild.findViewById(R.id.word_detail_pager);
		mLockHeadContainer = (LinearLayout) viewChild.findViewById(R.id.lock_head_container);
		mLockBottom = (ImageView) viewChild.findViewById(R.id.lock_bottom);
		mBackgroundImage = (ImageView) viewChild.findViewById(R.id.background_image);
		lock1234 = (PageControl) viewChild.findViewById(R.id.lock1234);
		return viewChild;
	}

	private void initViews() {
		// LogActivity.addLog("LockActivity initViews()");
		mRegisterReceiver();// 注册广播
		tm = (TelephonyManager) this.getSystemService(this.TELEPHONY_SERVICE);
		tm.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);// 设置电话状态监听
		int num = AppPreference.getLockScreenWordsNum(LockActivity.this);
		lock1234.setPointCount(num);
		createLockHeadView();
		createLockPagerView();
		creatPagerParent();
		creatVerticalViewPager();

		if (AppPreference.isFirstVisitLockScreen(mContext)) {// 锁屏引导界面
			lockGuidance();
			AppPreference.setFirstVisitLockScreen(mContext, false);
		}
	}

	void setBackGround() {
		String wallpaper = AppPreference.getLockScreenWallpaper(this);
		if (wallpaper.equals("default")) {
//			mBackgroundImage.setImageResource(AppPreference.getDefaultWallpaperImg(this));
			// mBackgroundImage.setBackgroundResource(AppPreference.getDefaultWallpaperImg(this));
			
			InputStream inputStream = getResources().openRawResource(AppPreference.getDefaultWallpaperImg(this));
			Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null,getOptions(1));
			mBackgroundImage.setImageBitmap(bitmap);
			
		} else if (wallpaper.equals("system")) {
			mBackgroundImage.setImageDrawable(BitmapUtil.getWallPaper(this, true));
			// mBackgroundImage.setBackgroundDrawable(BitmapUtil.getWallPaper(this,
			// true));
		} else {
//			Uri imageUri = Uri.parse(wallpaper);
//			LogUtil.d(imageUri.getPath()+","+wallpaper);
//			mBackgroundImage.setImageURI(null);
//			mBackgroundImage.setImageURI(imageUri);
			
			Bitmap bitmap;
			try {
				bitmap = BitmapFactory.decodeStream(this.getContentResolver().openInputStream(Uri.parse(wallpaper)),null, getOptions(2));
				mBackgroundImage.setImageBitmap(bitmap);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		// 锁屏使用非自带壁纸，底部显示“优趣背单词”几个字
		if (!wallpaper.equals("default"))
			mLockBottom.setVisibility(View.VISIBLE);
	}
	
	private BitmapFactory.Options getOptions(int inSampleSize){
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = false;
		options.inTempStorage = new byte[100*1024];   //为位图设置100k的缓存
		options.inPreferredConfig = Config.RGB_565;   //设置位图颜色显示方式,RGB_565占16位，默认占32位
		options.inPurgeable = true;                   //设置图片可以被回收
		options.inSampleSize = inSampleSize;
		return options;
	}

	boolean ifLockScreenGuideEquals1st = true;
	int indexOfGuidePages = 1;

	private void lockGuidance() {
		final LinearLayout lockGuidanceLayout = (LinearLayout) findViewById(R.id.lock_guidance);
		View viewLockGuidance = View.inflate(this, R.layout.activity_lockscreen_guide, null);
		final ImageView animationImage = (ImageView) viewLockGuidance.findViewById(R.id.lockscreen_guide_animation_image);
		final ImageView animationText = (ImageView) viewLockGuidance.findViewById(R.id.lockscreen_guide_animation_text);
		final Button btnText = (Button) viewLockGuidance.findViewById(R.id.lockscreen_guide_btnText);
		final LinearLayout animationLockGuide = (LinearLayout) viewLockGuidance.findViewById(R.id.lock_screen_animation);
		Animation animLeft = AnimationUtils.loadAnimation(this, R.anim.lockscreen_guide_left);
		final Animation animUp = AnimationUtils.loadAnimation(this, R.anim.lockscreen_guide_up);
		animationLockGuide.startAnimation(animLeft);
		btnText.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (ifLockScreenGuideEquals1st && indexOfGuidePages == 1) {
					animationImage.setImageResource(R.drawable.lock_screen_up);
					animationText.setImageResource(R.drawable.lock_screen_hint_text4);
					animationLockGuide.clearAnimation();
					animationLockGuide.startAnimation(animUp);
					indexOfGuidePages++;
				} else if (ifLockScreenGuideEquals1st && indexOfGuidePages == 2) {
					animationImage.setImageResource(R.drawable.lock_guide_setting);
					animationText.setVisibility(View.GONE);
					animationLockGuide.clearAnimation();
					btnText.setText("完成");
					ifLockScreenGuideEquals1st = false;
				} else
					lockGuidanceLayout.setVisibility(View.GONE);
			}

		});

		lockGuidanceLayout.addView(viewLockGuidance);
		lockGuidanceLayout.setVisibility(View.VISIBLE);
	}

	private void createLockHeadView() {
		View headView = View.inflate(this, R.layout.view_lock_head, null);
		time_text = (TextView) headView.findViewById(R.id.time_text);
		date_text = (TextView) headView.findViewById(R.id.date_text);
		power_text = (TextView) headView.findViewById(R.id.power_text);
		setTime();
		setDate();
		setPower("");
		mLockHeadContainer.addView(headView);
	}

	int currentItem = 0;
	int nextItem = 0;
	boolean isMoving = false;
	float XDown = -1;

	private void createLockPagerView() {
		// LogActivity.addLog("LockActivity createLockPagerView()");
		mWordList = WordFactory.getInstance(this).getWordForLock();
		// LogUtil.addLog("锁屏显示的单词为：" + mWordList.get(0).getLemma() + "," +
		// mWordList.get(1).getLemma() + "," + mWordList.get(2).getLemma());
		fragmentsList = new ArrayList<Fragment>();
		final int num = AppPreference.getLockScreenWordsNum(this);
		for (int i = 0; i < num; i++) {
			Fragment activityfragment = new WordDetailForLockFragment(mWordList.get(i));
			fragmentsList.add(activityfragment);
		}
		mPagerAdapter = new WordDetailForLockAdapter(this, getSupportFragmentManager(), fragmentsList);
		mPagerChild.setAdapter(mPagerAdapter);
		mPagerChild.setCurrentItem(0);
		setParentSlidEnable(false);
		WordFactory.getInstance(LockActivity.this).markCurrentLockedWord(mWordList.get(0));
		mPagerChild.setOffscreenPageLimit(OFFSCREEN_PAGE_LIMIT);

		mPagerChild.setOnPageChangeListener(new HorizontalViewPager.OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				mPagerAdapter.instantiateItem(mPagerChild, position);
				WordFactory.getInstance(LockActivity.this).markCurrentLockedWord(mWordList.get(position));
				if (position == num - 1) {
					setParentSlidEnable(true);
				} else
					setParentSlidEnable(false);
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				if (isMoving) {
					lock1234.moving(currentItem, nextItem, arg1, true);
				}
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				if (arg0 == 0) {// 滑动结束
					currentItem = mPagerChild.getCurrentItem();
				} else if (arg0 == 2) {// 滑动手指离开屏幕
					isMoving = false;
					XDown = -1;
					lock1234.leftActionAnimation(currentItem, mPagerChild.getCurrentItem());
					currentItem = mPagerChild.getCurrentItem();
				}
			}
		});
		mPagerChild.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				// case MotionEvent.ACTION_DOWN:
				// XDown = event.getX();
				// isMoving = true;
				// LogUtil.e("onTouch_ACTION_DOWN");
				// break;
				case MotionEvent.ACTION_MOVE:
					if (XDown > 0 && event.getX() > XDown && currentItem > 0) {
						nextItem = currentItem - 1;
						isMoving = true;
					} else if (XDown > 0) {
						nextItem = currentItem + 1;
						isMoving = true;
					}
					if (!isMoving) {
						XDown = event.getX();
					}
					break;
				}
				return false;
			}
		});
	}

	private void creatVerticalViewPager() {
		View v = new View(this);
		verticalPagerViewList = new ArrayList<View>();
		verticalPagerViewList.add(mPagerParent);
		verticalPagerViewList.add(v);
		mVerticalViewPager.setAdapter(new mVPagerAdapter());
		mVerticalViewPager.setOnPageChangeListener(new VerticalViewPager.OnPageChangeListener() {

			@Override
			public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
			}

			@Override
			public void onPageSelected(int position) {
				if (position == 1) {
					// virbate();// 震动
					finishMyActivity();
				}
			}

			@Override
			public void onPageScrollStateChanged(int state) {
			}
		});

	}

	private void creatPagerParent() {
		mPagerParent = new viewPagerParent(this);
		View v = new View(this);
		parentPagerViewList = new ArrayList<View>();
		parentPagerViewList.add(viewChild);
		parentPagerViewList.add(v);
		mPagerParent.setAdapter(new mParentPagerAdapter());
		mPagerParent.setOnPageChangeListener(new viewPagerParent.OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				if (arg0 == 1) {
					// virbate();// 震动
					finishMyActivity();
				}
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}
		});
	}

	public static void setPower(String power) {
		// TODO Auto-generated method stub
		if (!power.equals("")) {
			power_text.setText("正在充电" + power);
		} else if (power.equals("100%")) {
			power_text.setText("电量已满");
		} else {
			power_text.setText("");
		}
	}

	// 得到日期
	public static void setDate() {
		// TODO Auto-generated method stub
		String time = new SimpleDateFormat("MM月dd日").format(new Date());
		Calendar c = Calendar.getInstance();
		String week = String.valueOf(c.get(Calendar.DAY_OF_WEEK));
		if ("1".equals(week)) {
			week = "日";
		} else if ("2".equals(week)) {
			week = "一";
		} else if ("3".equals(week)) {
			week = "二";
		} else if ("4".equals(week)) {
			week = "三";
		} else if ("5".equals(week)) {
			week = "四";
		} else if ("6".equals(week)) {
			week = "五";
		} else if ("7".equals(week)) {
			week = "六";
		}
		time += "  星期" + week;
		date_text.setText(time);
	}

	// 得到系统时间
	public static void setTime() {
		// TODO Auto-generated method stub
		String time = new SimpleDateFormat("HH:mm").format(new Date());
		time_text.setText(time);
		// 监听到向上滑动解锁
	}

	// 设置当 有电话打进的时候或者还在通话状态中 解锁则finish本锁屏
	private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			super.onCallStateChanged(state, incomingNumber);
			if (state == TelephonyManager.CALL_STATE_RINGING || state == TelephonyManager.CALL_STATE_OFFHOOK) {

				String str = "";
				if (state == TelephonyManager.CALL_STATE_RINGING)
					str = "TelephonyManager.CALL_STATE_RINGING";
				else if (state == TelephonyManager.CALL_STATE_OFFHOOK)
					str = "TelephonyManager.CALL_STATE_OFFHOOK";
				// LogUtil.addLog("LockActivity监听到通话状态有变化:" + str);

				finishMyActivity();
			}
		}
	};

	@Override
	public void onAttachedToWindow() {
		this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		// super.onAttachedToWindow();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			return true;
		} else if (event.getKeyCode() == KeyEvent.KEYCODE_SEARCH) {
			return true;
		} else if (event.getKeyCode() == KeyEvent.KEYCODE_MENU) {
			return true;
		} else
			return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onResume() {
		super.onResume();
		// LogUtil.addLog("LockActivity onResume()");
		MobclickAgent.onResume(this);
	}

	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	public static Context getContext() {
		return mContext;
	}

	public void finishMyActivity() {
		Log.i("finish LockActivity", "success");
		// LogActivity.addLog("LockActivity finishMyActivity()结束锁屏界面运行");
		mUnregisterReceiver();
		finish();
	}

	private void mRegisterReceiver() {
		// 注册home键广播
		homeKeyReceiver = new HomeKeyEventBroadCastReceiver();
		IntentFilter filter1 = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		registerReceiver(homeKeyReceiver, filter1);
		// HomeKeyEventBroadCastReceiver.registerHomeKeyEventBroadCastReceiver(this);

		// 注册时间变化广播
		dateTimerReceiver = new DateTimeReceiver();
		IntentFilter filter2 = new IntentFilter();
		filter2.addAction(Intent.ACTION_TIME_TICK);
		filter2.addAction(Intent.ACTION_DATE_CHANGED);
		filter2.addAction(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(dateTimerReceiver, filter2);
	}

	private void mUnregisterReceiver() {
		try {
			if (homeKeyReceiver != null) {
				unregisterReceiver(homeKeyReceiver);
				homeKeyReceiver = null;
			}
			if (dateTimerReceiver != null) {
				unregisterReceiver(dateTimerReceiver);
				dateTimerReceiver = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}

	private class mVPagerAdapter extends VerticalPagerAdapter {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getCount() {
			return verticalPagerViewList.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(verticalPagerViewList.get(position));
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(verticalPagerViewList.get(position));
			return verticalPagerViewList.get(position);
		}
	}

	private class mParentPagerAdapter extends PagerAdapter {

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getCount() {
			return parentPagerViewList.size();
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(parentPagerViewList.get(position));
		}

		@Override
		public int getItemPosition(Object object) {
			return super.getItemPosition(object);
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container.addView(parentPagerViewList.get(position));
			return parentPagerViewList.get(position);
		}
	}

	public void setParentSlidEnable(boolean b) {
		isParentSlidEnable = b;
	}

	public static boolean getParentSlidEnable() {
		return isParentSlidEnable;
	}

	// // 震动一下下咯
	// private void virbate() {
	// Vibrator vibrator = (Vibrator) this
	// .getSystemService(Context.VIBRATOR_SERVICE);
	// vibrator.vibrate(200);
	// // MediaPlayer mp = MediaPlayer.create(this, R.raw.unlock);
	// // mp.start();
	//
	// // SoundPool soundPool;
	// // soundPool = new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);
	// // soundPool.load(this, R.raw.unlock, 1);
	// // soundPool.play(1, 1, 1, 0, 0, 1);
	// }
}
